package com.gomtel.smartdevice.ui.activity.tools;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.gomtel.smartdevice.R;
import com.gomtel.smartdevice.api.BleManager;
import com.gomtel.smartdevice.api.MessageManager;
import com.gomtel.smartdevice.base.WatchAppBaseActivity;
import com.gomtel.smartdevice.bean.UserContent;
import com.gomtel.smartdevice.bt.bt.BluetoothChatService;
import com.gomtel.smartdevice.bt.bt.Constants;
import com.gomtel.smartdevice.global.DataClass;
import com.gomtel.smartdevice.global.WatchApplication;
import com.gomtel.smartdevice.moudle.db.entity.AppConfigurationInfo;
import com.gomtel.smartdevice.moudle.db.entity.EcgDataInfo;
import com.gomtel.smartdevice.moudle.db.entity.SignsOfDataInfo;
import com.gomtel.smartdevice.moudle.event.CommonEvent;
import com.gomtel.smartdevice.moudle.event.EventCode;
import com.gomtel.smartdevice.moudle.rxtools.EventBusUtil;
import com.gomtel.smartdevice.ui.dialog.ProgressDialog;
import com.gomtel.smartdevice.ui.dialog.ShowDialog;
import com.gomtel.smartdevice.ui.view.MyProgress;
import com.gomtel.smartdevice.utils.CommonUtils;
import com.gomtel.smartdevice.utils.LogUtil;
import com.gomtel.smartdevice.utils.SystemUtil;
import com.gomtel.smartdevice.view.HeartBeatView;
import com.gomtel.smartdevice.widget.CalenderUtilsClass;
import com.mediatek.jni.Utils;

import java.util.List;

import butterknife.BindView;

/**
 * Created by Administrator on 2018/5/26 0026.
 * 心电测试
 */

public class EGCActivity extends WatchAppBaseActivity implements View.OnClickListener {

    @BindView(R.id.img_btn_black)
    ImageButton img_btn_black;
    @BindView(R.id.title_name)
    TextView title_name;
    @BindView(R.id.title_about)
    ImageButton title_about;
    @BindView(R.id.begin)
    Button begin;
    @BindView(R.id.pressure_exponent)
    TextView pressure_exponent;
    @BindView(R.id.tired_exponent)
    TextView tired_exponent;

    @BindView(R.id.hrv_status)
    TextView hrv_status;
    @BindView(R.id.biological_age)
    TextView biological_age;

    @BindView(R.id.progress)
    MyProgress progress;

    @BindView(R.id.egc)
    HeartBeatView egc;
    @BindView(R.id.stop)
    Button stop;

    @BindView(R.id.hint_layout)
    LinearLayout hint_layout;
    @BindView(R.id.egc_layout)
    LinearLayout egc_layout;

    String pressureExponent = "--";
    String biologicalAge = "--";
    String hrvStatus = "--";
    String recentlyTime = "--";
    String tiredExponent = "--";
    boolean ecgStatus = true; //按钮状态
    private int age;
    private int ss;
    //    private boolean status = true;
    private boolean messageReadStatus = false; //回调开始状态

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    if (progress != null) {
                        progress.setProgress(ss);
                    }
                    break;
                case 1:
                    ss = getResources().getInteger(R.integer.measure_time);
                    if (progress != null) {
                        progress.setProgress(ss);
                        messageReadStatus = false;
                        initProgressData();
                        stop.setText(getString(R.string.stop));
                        Log.e(TAG, "设置成功");
                    }
                    break;
            }
            return true;
        }
    });
    private ShowDialog showDialog;
    private ProgressDialog progressDialog;
    private ProgressDialog mConProgressDialog;

    @Override
    protected void registerEvent(CommonEvent commonevent) {

    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_egc;
    }

    @Override
    protected void initClass() {
        showDialog = ShowDialog.newInstance();
        progressDialog = showDialog.showProgressStatus(this, "准备中测试...");
        mConProgressDialog = showDialog.showProgressStatus(this, "正在连接心电测试...");
        mConProgressDialog.setCancelable(false);
        //mConProgressDialog.show();
    }

    @Override
    protected void initData() {
        ss = getResources().getInteger(R.integer.measure_time);
        SignsOfDataInfo signsOfDataInfo = dataManager.querySignsOfDataInfo(UserContent.UserName);
        if (signsOfDataInfo != null) {
            age = CalenderUtilsClass.getAgeByBirthDay(signsOfDataInfo.getBirthday());
        }
    }

    @Override
    protected void initView() {
        initProgressData();
        title_about.setVisibility(View.VISIBLE);
        title_name.setText(getString(R.string.ECG));
    }

    public void initProgressData() {
        List<EcgDataInfo> ecgDataInfos = dataManager.queryEcgDataInfo(UserContent.UserName);
        if (ecgDataInfos != null && ecgDataInfos.size() > 0) {
            EcgDataInfo ecgDataInfo = ecgDataInfos.get(ecgDataInfos.size() - 1);
            pressureExponent = ecgDataInfo.getPressureExponent();
            biologicalAge = ecgDataInfo.getBiologicalAge();
            hrvStatus = ecgDataInfo.getHRVStatus();
            recentlyTime = ecgDataInfo.getRecentlyTime();
            tiredExponent = ecgDataInfo.getTiredExponent();
        }
        SystemUtil.textMagicTool(this, pressure_exponent, "压力指数\n", pressureExponent);
        SystemUtil.textMagicTool(this, tired_exponent, "疲劳指数\n", tiredExponent);
        SystemUtil.textMagicTool(this, hrv_status, "HRV状态\n", hrvStatus);
        SystemUtil.textMagicTool(this, biological_age, "生理年龄\n", biologicalAge);
        progress.setText("近期测量:" + recentlyTime);
        Log.e(TAG, recentlyTime);
    }

    @Override
    protected void initListener() {
        img_btn_black.setOnClickListener(this);
        title_about.setOnClickListener(this);
        begin.setOnClickListener(this);
        stop.setOnClickListener(this);
        HrvListener();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_btn_black:
                finish();
                break;
            case R.id.title_about:
//                ecgRefresh((float) (Math.random() * 4000));
                Intent intent = new Intent(EGCActivity.this, SignsOfHistoryActivity.class);
                intent.putExtra("ActionType", "0");
                startActivity(intent);
                break;
            case R.id.begin:
//                ecgRefresh(0f); //心电数据接入
                if (!DataClass.onlineStatus) {
                    toastUtil.showToast("设备未连接 ... ");
                    return;
                }
                if (isCollection[0] && count <= 3) {
                    CommonUtils.showToast(getApplicationContext(), "数据正在加载中,请稍后");
                    return;
                }
                progressDialog.show();
                sendToHrv();
                EventBusUtil.sendEvent(new CommonEvent(EventCode.HRV_MEASURE));
                hint_layout.setVisibility(View.GONE);
                egc_layout.setVisibility(View.VISIBLE);
                egc.setVisibility(View.VISIBLE);
                if (!ecgStatus) {
                    ecgStatus = true;
                }
                timeKeeping();
                break;
            case R.id.stop:
                ecgStatus = !ecgStatus;
                /*if (stop.getText().toString().equals(R.string.begin)) {
                    stop.setText(R.string.stop);
                    sendToHrv();
                    if (!ecgStatus) {
                        ecgStatus = true;
                    }
                    timeKeeping();
                }*/
                handler.sendEmptyMessage(0);
                hint_layout.setVisibility(View.VISIBLE);
                egc_layout.setVisibility(View.GONE);
                break;
        }
    }

    public void timeKeeping() {
        if (!ecgStatus) {
            return;
        }
//        if (status) {
//            status = false;
//            sendToHrv();
//        }
        WatchApplication.executorService.submit(() -> {
            try {
                Thread.sleep(1000);
                if (messageReadStatus) {
                    handler.sendEmptyMessage(0);
                    ss--;
                }
                if (!DataClass.onlineStatus) {
                    EventBusUtil.sendEvent(new CommonEvent(EventCode.LOCAL_AREA_LINKS));
                }
                if (ss > 0) {
                    timeKeeping();
                } else {
                    handler.sendEmptyMessage(1);
                    /*if (DataClass.onlineStatus) {
                        toastUtil.showToast("测量成功");
                    } else {
                        toastUtil.showToast("测量失败");
                    }*/
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    }

    private void HrvListener() {
        //心电图的回调
        /*MessageManager.getInstance().setConnectHrvListener(hrvDataResponse -> runOnUiThread(() -> {
            switch (hrvDataResponse.getType()) {
                case Constants.MESSAGE_STATE_CHANGE:
                    if (hrvDataResponse.getStatus() == BluetoothChatService.STATE_CONNECTED) {
                        //toastUtil.showToast("Hrv准备完成");
                        LogUtil.e(TAG, "Hrv准备完成");
                    }
                    break;
                case Constants.MESSAGE_READ:
                    messageReadStatus = true;
                    if (progressDialog != null && progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }
                    if (hrvDataResponse.getMv() != 0 && hrvDataResponse.getTimeStamp() != 0) {
                        //显示心电图
                        egc.addECG(hrvDataResponse.getMv(), hrvDataResponse.getTimeStamp());
                    }
                    break;
            }
        }));*/

        //心电的数据回调
        MessageManager.getInstance().setHrvListener(hrvBean -> runOnUiThread(() -> {
            String status = "";
            refreshLogView("SDNN = " + hrvBean.getSDNN() + " hr = " + hrvBean.getHr() + "  LF_HF = " + hrvBean.getLF_HF() + "  LF = " + hrvBean.getLF() + " HF = " + hrvBean.getHF());
            if (hrvBean.getLF() == -1000 && hrvBean.getSDNN() == -1000 && hrvBean.getHF() == -1000) {
                refreshLogView("测量失败");
                toastUtil.showToast("测量失败");
                handler.sendEmptyMessage(1);
                ecgStatus = true;
                return;
            }

            int pressure = Utils.get_pressure_index_from_sdnn(hrvBean.getSDNN() / 1000, age);
            int fatigue = Utils.get_fatigue_index_from_hrv(hrvBean.getLF() / 1000, hrvBean.getHF() / 1000);
            /**
             *    hrvStatus 有5中状态:
             *       HrvStatus.API_NORMAL = 0;    正常
             *       HrvStatus.API_EXCITED = 1;   兴奋
             *       HrvStatus.API_GOOD = 2;      良好
             *       HrvStatus.API_STRESSED = 3;  焦虑
             *       HrvStatus.API_DEPRESSED = 4; 抑郁
             */
            int hrvStatus = Utils.getHrvState(age, hrvBean.getSDNN(), hrvBean.getHr());
            int estAge = Utils.getEstAge(hrvBean.getSDNN(), age, 120);
            switch (hrvStatus) {
                case 0:
                    status = "正常";
                    break;
                case 1:
                    status = "兴奋";
                    break;
                case 2:
                    status = "良好";
                    break;
                case 3:
                    status = "焦虑";
                    break;
                case 4:
                    status = "抑郁";
                    break;
            }
            dataManager.insertEcgDataInfo(new EcgDataInfo(UserContent.UserName, CalenderUtilsClass.getCurrentDay(true), String.valueOf(pressure), String.valueOf(fatigue), status, String.valueOf(estAge)));
            handler.sendEmptyMessage(1);
            refreshLogView("压力指数:" + pressure + "  疲劳指数:" + fatigue + "  心电状态:" + status + "  生理年龄:" + estAge);
        }));
    }

    private void refreshLogView(String msg) {
        LogUtil.e(TAG, "refreshLogView : " + msg);
    }

    private boolean isSend = false;

    @SuppressLint("NewApi")
    @Override
    protected void onResume() {
        super.onResume();
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_ADMIN) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.BLUETOOTH_ADMIN}, 200);
        } else {
            if (!isSend) {
                isSend = true;
                CommonUtils.getHandler().postDelayed(this::sendToHrv, 1000);
            }
        }
    }

    @Override
    protected void onRestart() {
        isSend = false;
        super.onRestart();
    }

    private final boolean[] isCollection = {true};
    private int count = 0;

    private void sendToHrv() {
        if (BleManager.getInstance().getStatus() == BleManager.CONNECT_STATUS_CONNECTED) {
            AppConfigurationInfo appConfigurationInfo = dataManager.queryAppConfigurationInfo(UserContent.UserName);
            if (appConfigurationInfo != null) {
                MessageManager.getInstance().connectHrv(appConfigurationInfo.getMAC(), hrvDataResponse -> {
                    if (isFinishing()) {
                        return;
                    }
                    switch (hrvDataResponse.getType()) {
                        case Constants.MESSAGE_STATE_CHANGE:
                            if (hrvDataResponse.getStatus() == BluetoothChatService.STATE_CONNECTED) {
                                Log.e(TAG, "Hrv准备完成");
                                isCollection[0] = false;
                                if (mConProgressDialog != null && mConProgressDialog.isShowing()) {
                                    mConProgressDialog.dismiss();
                                }
                            }
                            break;
                        case Constants.MESSAGE_READ:
                            isCollection[0] = false;
                            messageReadStatus = true;
                            if (progressDialog != null && progressDialog.isShowing()) {
                                progressDialog.dismiss();
                            }
                            if (hrvDataResponse.getMv() != 0 && hrvDataResponse.getTimeStamp() != 0) {
                                //显示心电图
                                egc.addECG(hrvDataResponse.getMv(), hrvDataResponse.getTimeStamp());
                            }
                            break;
                    }
                    CommonUtils.getHandler().postDelayed(() -> {
                        if (isCollection[0]) {
                            count++;
                            if (count > 3) {
                                CommonUtils.showToast(getApplicationContext(), "数据加载异常,请重新进入");
                                CommonUtils.getHandler().removeCallbacks(null);
                                finish();
                                return;
                            }
                            try {
                                //MessageManager.getInstance().connectHrv(appConfigurationInfo.getMAC(), null);
                                sendToHrv();
                            } catch (Throwable e) {
                                e.printStackTrace();
                                CommonUtils.showToast(getApplicationContext(), "数据加载异常,请重新进入");
                                finish();
                            }
                        }
                    }, 3000);
                });
            }
        } else {
            LogUtil.e(TAG, "请先连接手表设备蓝牙");
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 200) {
            if (!isSend) {
                isSend = true;
                CommonUtils.getHandler().postDelayed(this::sendToHrv, 1000);
            }
        }
    }

    @Override
    protected void onDestroy() {
//        status = true;
        //MessageManager.getInstance().setConnectHrvListener(null);
        super.onDestroy();
    }
}
